// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
    throwOnNotFound: false
})
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        const result = await db.runTransaction(async transaction => {
            const {
                id,
                attachments,
                textContent,
                createDate,
                province,
                city
            } = event.article
            let params = {}
            if (id) {
                params = {
                    _id: _.eq(id)
                }
            }
            const item = await db.collection('article').where(params).get()
            const {
                attachments: fileList,
                textContent:oldTextContent
            } = item.data[0]
            const sameState = oldTextContent == textContent?false:true
            const remveList = fileList.filter(item => {
                if (attachments.includes(item)) return false
                return true
            })
            let delImgResult = undefined
            if(remveList.length>0){
                delImgResult = await cloud.deleteFile({
                    fileList: remveList
                })
            }
            let result = await db.collection('article').where(params).update({
                data: {
                    attachments: _.set(attachments),
                    textContent: textContent,
                    remark:_.set(`修改于 ${createDate}`),
                    province: province,
                    city: city
                }
            })
            if(remveList.length>0 && delImgResult && result){
                return result
            }else if(sameState && result){
                if(remveList.length>0 && delImgResult){
                    return result
                }else if(remveList.length == 0){
                    return result
                }else{
                await transaction.rollback({remveList,delImgResult,result})
                }
            }else{
                if(fileList.length !== attachments.length) return result
                await transaction.rollback({remveList,delImgResult,result})
            }
        })
        return {
            result
        }
    } catch(e) {
        return {
            result:false,
            e
        }
    }
}